package com.zeng.springboot03web.controller;

import com.zeng.springboot03web.dao.DepartmentDao;
import com.zeng.springboot03web.dao.EmployeeDao;
import com.zeng.springboot03web.pojo.Department;
import com.zeng.springboot03web.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeDao employeeDao;
    @Autowired
    DepartmentDao departmentDao;

    @RequestMapping("/emps")
    public String list(Model model) {
        Collection<Employee> employees = employeeDao.getALL();
        model.addAttribute("emps", employees);
        return "emp/list";
    }

    //
    @GetMapping("/emp")
    public String add(Model model) {
        Collection<Department> departments = departmentDao.getDepartments();
        System.out.println("进来了");
        model.addAttribute("departments", departments);
        return "emp/add";
    }

    //    表单用post提交
    @PostMapping("/emp")
    public String addEmp(Employee employee) {
        System.out.println(employee);
        System.out.println("也进来了");
//        System.out.println("save=>"+employee);
        employeeDao.add(employee);
        return "redirect:/emps";// forword
    }

    // 传过来的id需要加花括号
    @GetMapping("emp/{id}")
    public String update(@PathVariable("id") int id,Model model){
        Employee employee = employeeDao.getEmployeeById(id);
        model.addAttribute("emp",employee);
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/update";
    }

    @PostMapping("/update")
    public String update(Employee employee) {
        employeeDao.add(employee);
        return "redirect:/emps";
    }

    @GetMapping("/delete/{id}")
    public String deleteEmployeeById(@PathVariable("id") int id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
